package org.javaboy.timelog.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;

// time.log.enabled=true
@ConditionalOnProperty(prefix = "time.log", name = "enabled", havingValue = "true", matchIfMissing = true)
@Component
@Aspect
@EnableAspectJAutoProxy
public class TimeLogAutoConfiguration {
    private static final Logger logger = LoggerFactory.getLogger(TimeLogAutoConfiguration.class);

    @Pointcut("@annotation(org.javaboy.timelog.anno.TimeLog)||@within(org.javaboy.timelog.anno.TimeLog)")
    public void pc() {

    }

    @Around("pc()")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        //获取方法的详细名称
        String methodName = signature.toLongString();
        long startTime = System.currentTimeMillis();
        Object proceed = pjp.proceed();
        long endTime = System.currentTimeMillis();
        logger.info("{} 方法执行耗时 {} 毫秒", methodName, (endTime - startTime));
        return proceed;
    }
}
